package com.sgb.link.view.widget.location;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.sgb.link.R;
import com.sgb.link.databinding.CitySelectionLayoutBinding;
import com.sgb.link.entity.AMapAddressEntity;
import com.sgb.link.entity.trip.AirportCityEntity;
import com.swgk.core.customview.WSTextView;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Describe:   食住行 城市选择器
 * Author:  yangLei
 * Date:    2021/7/29
 */
public class CitySelectionView extends RelativeLayout implements View.OnClickListener {

    private Context mContext;
    private CitySelectionLayoutBinding mBinding;

    /**
     * 热门城市相关
     */
    private List<AMapAddressEntity> hotStrings;
    private WrapLinearLayout hotWrap;
    private SimpleTextAdapter textAdapter;
    private SortAdapter adapter;

    private WSTextView currCityTV;
    private RecyclerView hotCityGrid;

    /**
     * 汉字转换成拼音相关类
     */
    private CharacterParser characterParser;
    private List<SortModel> SourceDateList = new ArrayList<>();
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private List<AirportCityEntity> addressItems;

    //事件相关
    private CityCheckedClickListener checkedClickListener;

    public CitySelectionView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater inflater = LayoutInflater.from(context);
        mBinding = DataBindingUtil.inflate(inflater, R.layout.city_selection_layout, this, true);
        this.mContext = context;
        initView();
    }

    public CityCheckedClickListener getCheckedClickListener() {
        return checkedClickListener;
    }

    public void setCheckedClickListener(CityCheckedClickListener checkedClickListener) {
        this.checkedClickListener = checkedClickListener;
    }

    public void initHot(List<AirportCityEntity> hotData) {
        textAdapter = new SimpleTextAdapter(mContext, hotData);
        hotCityGrid.setAdapter(textAdapter);
        textAdapter.setItemClickListener((position, text) -> setResult(text));
    }

    /**
     * 初始化所有组件
     */
    private void initView() {
        //头布局初始化
        View headerView = LayoutInflater.from(mContext).inflate(R.layout.city_select_list_header_layout, null);
        currCityTV = headerView.findViewById(R.id.curr_city);
        currCityTV.setVisibility(GONE);
        hotCityGrid = headerView.findViewById(R.id.hot_city_grid);

        mBinding.sortListView.addHeaderView(headerView);

        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();

        mBinding.sideBar.setTextView(mBinding.dialog);
        mBinding.sideBar.setVisibility(GONE);
        hotCityGrid.setLayoutManager(new GridLayoutManager(mContext, 3));

        //设置右侧触摸监听
        mBinding.sideBar.setOnTouchingLetterChangedListener(s -> {
            //该字母首次出现的位置
            int position = adapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                mBinding.sortListView.setSelection(position + 1);
            }

        });

        mBinding.sortListView.setOnItemClickListener((parent, view, position, id) -> {
            //这里要利用adapter.getItem(position)来获取当前position所对应的对象
            String cityNo = ((SortModel) adapter.getItem(position - 1)).getNo();
            AirportCityEntity entity = new AirportCityEntity("", "", cityNo,
                    ((SortModel) adapter.getItem(position - 1)).getName(), "");
            if (!TextUtils.isEmpty(entity.getCityName()) && !TextUtils.isEmpty(entity.getCityCode())) {
                setResult(entity);
            }
        });

    }

    /**
     * 刷新城市列表数据
     */
    private void notifyCityList() {
        SourceDateList = filledData(addressItems);
        Collections.sort(SourceDateList, pinyinComparator);
        adapter = new SortAdapter(mContext, SourceDateList);
        mBinding.sortListView.setAdapter(adapter);

        //只把首字母存在的添加进导航
        List<String> stringList = new ArrayList<>();
        for (int j = 0; j < SourceDateList.size(); j++) {
            String sort = characterParser.getSelling(SourceDateList.get(j).getName()).substring(0, 1).toUpperCase();
            if (!stringList.contains(sort)) {
                stringList.add(sort);
            }
        }
        mBinding.sideBar.setB(stringList.toArray(new String[0]));
        mBinding.sideBar.setVisibility(VISIBLE);
    }

    /**
     * 为ListView填充数据
     *
     * @param data
     * @return
     */
    private List<SortModel> filledData(List<AirportCityEntity> data) {
        List<SortModel> mSortList = new ArrayList<SortModel>();
        for (int i = 0; i < data.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(data.get(i).getCityName());
            sortModel.setNo(data.get(i).getCityCode());
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(data.get(i).getCityName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    public void filterData(String filterStr, List<AirportCityEntity> data) {
        List<SortModel> filterDateList = new ArrayList<>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            filterDateList = filledData(data);
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);

    }

    /**
     * 初始化所有城市信息
     *
     * @param data
     */
    public void initAddressData(List<AirportCityEntity> data) {
        if (addressItems == null) {
            addressItems = new ArrayList<>();
        } else
            addressItems.clear();

        if (data.size() <= 0) {
            MToast.showToast(mContext, "获取城市列表失败");
            return;
        }

        for (AirportCityEntity datum : data) {
            addressItems.add(new AirportCityEntity(datum.getAirportCode(), datum.getAirportName(), datum.getCityCode(), datum.getCityName(),
                    datum.getCityPinYin()));
        }

        //通知列表加载
        notifyCityList();
    }


    private void setResult(AirportCityEntity entity) {
//        MToast.showLongToast(mContext, "选择了" + currCity);
        if (checkedClickListener != null) {
            checkedClickListener.onCheckedResult(entity);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }


    public interface CityCheckedClickListener {

        void onCheckedResult(AirportCityEntity addressEntity);
    }
}
